#!/usr/bin/env python

"""
@file tools/Classes.python/class.FoldController.py

@date 29-dec-2012

@author Youri Hoogstrate

@version 1.3.6

@section LICENSE
yh-kt-fold can predict RNA 2D structures including K-turns.
Copyright (C) 2012-2013 Youri Hoogstrate

This file is part of yh-kt-fold.

yh-kt-fold is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

yh-kt-fold is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""



import shlex
import subprocess



class foldController:
	def __init__(self,seq):
		seq = seq.upper()
		seq = seq.replace(" ","")
		seq = seq.replace("'","")
		seq = seq.replace("T","U")
		seq = seq.replace("\"","")
		self._seq = seq
	
	def setKTurnMotif(self,kturnname,motif5p,motif3p,bonds):
		self._kturnname = kturnname
		self._motif5p = motif5p
		self._motif3p = motif3p
		self._bonds = bonds
	
	def setKTurn(self,de):
		fh = open("kturn_data.txt","w")
		fh.write("\n>"+self._kturnname+"\n")
		fh.write("5="+self._motif5p+"\n")
		fh.write("x="+self._bonds+"\n")
		fh.write("3="+self._motif3p+"\n")
		fh.write("e="+str(de)+"\n\n")
		fh.close()
	
	def findKTurnEnergies(self,energy_t,energy_b,structure_t,structure_b):
		ans = []
		
		if(not structure_t):
			self.setKTurn(energy_t);
			structure_t = self.runFolding()
		
		if(not structure_b):
			self.setKTurn(energy_b)
			structure_b = self.runFolding()
		
		if(structure_t['structure'] != structure_b['structure']):
			if( (energy_t - energy_b) < 0.01):
				ans.append([energy_t,energy_b,structure_t,structure_b])
			else:
				energy_c = 0.5*(energy_b+energy_t)
				
				for item in self.findKTurnEnergies(energy_c,energy_b,False,structure_b):
					ans.append(item)
				
				for item in self.findKTurnEnergies(energy_t,energy_c,structure_t,False):
					ans.append(item)
		
		return ans
	
	def runFolding(self):
		cmd = './yh-kt-fold -s '+self._seq
		args = shlex.split(cmd)
		output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
		output = output.split("\n")
		
		output_new = []
		
		nkturns = 0
		
		for line in output:
			if(line.strip() != ''):
				if(line[0] == '['):
					nkturns += 1
				elif(line[0] != '*'):
					output_new.append(line)
		
		output = output_new
		
		print output
		
		output[2] = output[2].strip()
		
		de = round(self.findDE(output[3]),4)
		
		return {'de':de,'structure':output[2],'nkturns':nkturns}
	
	def isNC(self,b1,b2):
		s = sorted([b1,b2])
		if(s[0] == 'A' and s[1] == 'U'):
			return True
		elif(s[0] == 'C' and s[1] == 'G'):
			return True
		elif(s[0] == 'G' and s[1] == 'U'):
			return True
		else:
			return False
	
	def findDE(self,string):
		return float(string.split('dE')[1].lstrip().split()[0])



